package com.lottery.im.module.tim.message;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.module.chat.adapter.ChatAdapter;
import com.lottery.im.module.main.ui.VideoActivity;
import com.lottery.im.module.tim.utils.TimFileUtil;
import com.lottery.im.widget.shapeimageview.CustomShapeImageView;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.ext.ugc.TIMUGCCover;
import com.tencent.imsdk.ext.ugc.TIMUGCElem;
import com.tencent.imsdk.ext.ugc.TIMUGCVideo;
import java.io.File;

/**
 * 小视频消息
 */

public class UGCMessage extends Message {
  private static final String TAG = "UGCMessage";

  public UGCMessage(TIMMessage message) {
    this.message = message;
  }

  public UGCMessage(String filePath, String coverPath, long duration) {
    message = new TIMMessage();

    TIMUGCElem elem = new TIMUGCElem();
    TIMUGCCover cover = new TIMUGCCover();
    File file = new File(coverPath);
    int height = 0, width = 0;
    if (file.exists()) {
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(coverPath, options);
      height = options.outHeight;
      width = options.outWidth;
    }
    cover.setHeight(height);
    cover.setWidth(width);
    cover.setType("PNG");
    TIMUGCVideo video = new TIMUGCVideo();
    video.setType("MP4");
    video.setDuration(duration);
    elem.setCover(cover);
    elem.setVideo(video);

    elem.setVideoPath(filePath);
    elem.setCoverPath(coverPath);
    message.addElement(elem);
  }

  /**
   * 显示消息
   *
   * @param viewHolder 界面样式
   * @param context 显示消息的上下文
   */
  @Override
  public void showMessage(final ChatAdapter.ViewHolder viewHolder, final Context context) {
    clearView(viewHolder);
    if (checkRevoke(viewHolder)) return;
    final TIMUGCElem e = (TIMUGCElem) message.getElement(0);
    switch (message.status()) {
      case SendFail:
      case Sending:
        showSnapshot(viewHolder,
            BitmapFactory.decodeFile(e.getCoverPath(), new BitmapFactory.Options()));
        break;
      case SendSucc:
        final TIMUGCCover snapshot = e.getCover();
        if (TimFileUtil.isCacheFileExist(e.getFileId())) {
          showSnapshot(viewHolder,
              BitmapFactory.decodeFile(TimFileUtil.getCacheFilePath(e.getFileId()),
                  new BitmapFactory.Options()));
        } else {
          snapshot.getImage(TimFileUtil.getCacheFilePath(e.getFileId()), new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onSuccess() {
              showSnapshot(viewHolder,
                  BitmapFactory.decodeFile(TimFileUtil.getCacheFilePath(e.getFileId()),
                      new BitmapFactory.Options()));
            }
          });
        }
        final String fileName = e.getFileId() + "_video";
        if (!TimFileUtil.isCacheFileExist(fileName)) {
          e.getVideo().getVideo(TimFileUtil.getCacheFilePath(fileName), new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onSuccess() {
              setVideoEvent(viewHolder, fileName, context);
            }
          });
        } else {
          setVideoEvent(viewHolder, fileName, context);
        }
        break;
    }
    showStatus(viewHolder);
  }

  /**
   * 获取消息摘要
   */
  @Override
  public String getSummary() {
    String str = getRevokeSummary();
    if (str != null) return str;

    StringBuilder result = new StringBuilder();

    TIMGroupMemberInfo senderGroupMemberProfile = message.getSenderGroupMemberProfile();
    if (null != senderGroupMemberProfile) {
      // 说明这是群聊消息
      if (TextUtils.isEmpty(message.getSenderGroupMemberProfile().getNameCard())) {
        // 有自己的群名片
        result.append(message.getSenderProfile().getNickName() + "：");
      } else {
        // 无自己的群名片
        result.append(message.getSenderGroupMemberProfile().getNameCard() + "：");
      }
    }
    result.append(MyApplication.getInstance().getString(R.string.summary_video));
    return result.toString();
  }

  /**
   * 保存消息或消息文件
   */
  @Override
  public void save() {

  }

  /**
   * 显示缩略图
   */
  private void showSnapshot(final ChatAdapter.ViewHolder viewHolder, final Bitmap bitmap) {
    if (bitmap == null) return;
    RelativeLayout layout =
        (RelativeLayout) LayoutInflater.from(MyApplication.getInstance())
            .inflate(R.layout.layout_message_ugc, null);
    CustomShapeImageView imageView = layout.findViewById(R.id.iv_pic);
    ViewGroup.LayoutParams lp = imageView.getLayoutParams();
    lp.width = bitmap.getWidth() * lp.height / bitmap.getHeight();
    imageView.setLayoutParams(lp);
    imageView.setImageBitmap(bitmap);
    getBubbleView(viewHolder).addView(layout);
  }

  private void showVideo(String path, Context context) {
    if (context == null) return;
    final TIMUGCElem e = (TIMUGCElem) message.getElement(0);
    File file = new File(path);
    if (file.length() < e.getVideo().getSize()) return;
    Intent intent = new Intent(context, VideoActivity.class);
    intent.putExtra("path", path);
    context.startActivity(intent);
  }

  private void setVideoEvent(final ChatAdapter.ViewHolder viewHolder, final String fileName,
      final Context context) {
    getBubbleView(viewHolder).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        showVideo(TimFileUtil.getCacheFilePath(fileName), context);
      }
    });
  }
}